package com.mall.thirdparth.pay.service.impl;

import com.mall.thirdparth.pay.config.WxPayConfig;
import com.mall.thirdparth.pay.model.dto.OrderPayReqDto;
import com.mall.thirdparth.pay.model.dto.OrderQueryReqDto;
import com.mall.thirdparth.pay.model.vo.OrderPayRespVo;
import com.mall.thirdparth.pay.model.vo.OrderQueryRespVo;
import com.mall.thirdparth.pay.service.OrderPayService;
import com.mall.thirdparth.pay.service.impl.inner.XcxOrderPayService;
import com.mall.thirdparth.pay.util.HttpServletUtils;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * @ClassName OrderPayServiceImpl
 * @Author ymx
 * @Description 订单支付服务
 * @Date 2023/12/21
 **/
@Service
public class OrderPayServiceImpl implements OrderPayService {

    private static final Logger log = LoggerFactory.getLogger(OrderPayServiceImpl.class);

    @Resource
    WxPayConfig wxPayConfig;

    @Resource
    private RSAAutoCertificateConfig rsaAutoCertificateConfig;

    @Resource
    private XcxOrderPayService xcxOrderPayService;

    @Override
    public OrderPayRespVo createPrePayOrder(OrderPayReqDto payOrderReqDto) throws Exception {
        String commonLog = "【订单支付】-【创建预支付订单】用户openId:" + payOrderReqDto.getOpenId()+
            ", 订单:" + payOrderReqDto.getOrderNo() + ",";

        // 校验支付金额
        if (payOrderReqDto.getTotalPrice() <= 0) {
            log.error(commonLog + "支付金额超出限制");
            return null;
        }

        // 创建预支付订单
        OrderPayRespVo orderPayRespVo = xcxOrderPayService.createPrePayOrder(payOrderReqDto, commonLog);
        return orderPayRespVo;
    }

    @Override
    public Map<String, String> payNotify(HttpServletRequest request) {
        // 支付回调
        try {
            String commonLog = "【订单支付】-【支付回调】" + HttpServletUtils.getRequestBody(request) + ",";
            Map<String, String> payMap = xcxOrderPayService.payNotify(request, commonLog);
            return payMap;
        } catch (IOException e) {
            log.info("payNotify获取支付回调失败", e);
        }
        return null;
    }

    @Override
    public OrderQueryRespVo queryOrder(OrderQueryReqDto orderQueryReqDto) {
        String commonLog = "【订单支付】-【根据商户订单号查询订单】商户订单号：" + orderQueryReqDto.getOrderNo() + ",";
        // 根据商户订单号查询订单
        return xcxOrderPayService.queryOrder(orderQueryReqDto.getOrderNo(), commonLog);
    }

}
